<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Read_attempts_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    public function countArr($arr, $query) {
      $counter = 0;
      foreach ($arr as $key) {
        $counter++;
      }
      $arr[$counter] = $query;
      return $arr;
  }

    public function search($zone, $mtr_rdr, $from, $to){
       $d1 = '';
       $d2 = '';
       if(empty($from)){
        $d1 = $to;
       }else{
        $d1 = $from;
       }

       if(empty($to)){
        $d2 = $from;
       }else{
        $d2 = $to;
       }

        $sql = "";
        $sql1 = ""; 
        $sql2 = "";
        $sql3 = "";
        $sql4 = "";
        $sql5 = "";
        $arr = array();
        if(!empty($zone)){
          $sql1 = " zone = '". $zone ."' ";
          array_push($arr,$sql1);
        }
        if(!empty($mtr_rdr)){
          $sql2 = " meter_reader_id = '". $mtr_rdr ."' ";
          array_push($arr,$sql2);
        }

         if(!empty($from) || !empty($to)){
         // $sql3 = "read_time >= IFNULL('".$from."','".$to."') AND read_time <= IFNULL('".$to."','".$from."') ";
          $sql3 = " DATE_FORMAT(STR_TO_DATE(read_time, '%d-%m-%Y'),'%d-%m-%Y  ') BETWEEN 
                  IFNULL(DATE_FORMAT(STR_TO_DATE('".$d1."', '%d-%m-%Y'),'%d-%m-%Y ') ,DATE_FORMAT('".$d2."','%d-%m-%Y  ')) 
                  AND IFNULL(DATE_FORMAT(STR_TO_DATE('".$d2."', '%d-%m-%Y'),'%d-%m-%Y ') ,DATE_FORMAT('".$d1."','%d-%m-%Y  ')) ";
          array_push($arr,$sql3);
        }

        $where = "WHERE ".implode(' AND ',$arr);

        $sql = "SELECT * FROM ubs_read_attempts_logs_v ".$where;
        //echo $sql;
        $q = $this->db->query($sql);
        return $q->result();
    }

    public function getzoning() {
      $query = $this->db->get('ar_zone1_values_v');
      return $query->result();
    }
    public function getusers(){
        return $this->db->query('SELECT au.user_id, CONCAT(au.first_name," ",au.last_name) name FROM app_users au,app_user_roles aur
    WHERE au.user_id = aur.user_id AND role_id = 19' )->result();
    }
}